<?php
class dbTool{
    private static function connectDB():array
    {
        $config=readConfig("db");
        $host=$config["host"];
        $user=$config["user"];
        $pass=$config["pass"];
        $port=$config["port"];
        $name=$config["name"];
//        print_r($config);
        $conn=mysqli_connect($host,$user,$pass,$name,$port);
        if ($conn){
            return ["status"=>"success","conn"=>$conn];
        }else{
            return ["status"=>"fail","reason"=>mysqli_connect_error()];
        }
    }
    public static function testDB():array
    {
        $a=self::connectDB();
//        print_r($a);
        return [];
    }

    public static function select(string $tableName,string $cols,string $where=""):array
    {
        $a=self::connectDB();
        if ($a["status"]=="success"){
            $conn=$a["conn"];
            $sql = "SELECT $cols FROM $tableName";
            if (strlen($where)>0){
                $sql.=" WHERE $where";
            }
            $r=mysqli_query($conn,$sql);

            if ($r){
                $data=array();
                while($row=mysqli_fetch_array($r,MYSQLI_ASSOC)){
                    array_push($data,$row);
                }
                return ["status"=>"success","data"=>$data];
            }else{
                return ["status"=>"fail","reason"=>mysqli_error($conn)];
            }
        }else{
            return $a;
        }
    }

    public static function insert(string $tableName,array $cols,array $values):array
    {
        $a=self::connectDB();
        if ($a["status"]=="success"){
            $conn=$a["conn"];
            $sql = "INSERT INTO `$tableName`\n (";
            foreach ($cols as $col) {
                $sql.="$col,";
            }
            $sql=substr($sql,0,strlen($sql)-1);
            $sql.=")\n VALUES \n(";
            foreach ($values as $value) {
                $sql.="\"$value\",";
            }
            $sql=substr($sql,0,strlen($sql)-1);
            $sql.=")";
//            echo $sql."<br>";
//            consoleLog($sql);
//            file_put_contents("log",$sql);
            $r=mysqli_query($conn,$sql);
            if ($r){
                return ["status"=>"success"];
            }else{
                return ["status"=>"fail","reason"=>mysqli_error($conn),"sql"=>$sql];
            }
        }else{
            return $a;
        }
    }
}